<template>
  <van-list
    v-model="loading"
    :finished="finished"
    finished-text="没有更多了"
    :error.sync="error"
    error-text="请求失败，点击重新加载"
    @load="onLoad"
  >
    <comment-item
      v-for="(comment, index) in list"
      :key="index"
      :comment="comment"
      @reply-click="$emit('reply-click', $event)"
    />
  </van-list>
</template>
<script>
import { getComments } from '@/api/comment'
import commentItem from '../components/comment-item.vue'
export default {
  name: 'CommentList',
  components: { commentItem },
  props: {
    source: {
      type: String,
      required: true
    },
    list: {
      type: Array,
      default: () => []
    },
    type: {
      type: String,
      validator(val) {
        return ['a', 'c'].includes(val)
      },
      default: 'a'
    }
  },
  data() {
    return {
      // list: [],  评论列表
      loading: false, // 上拉加载更多的 loading
      error: false,
      finished: false, // 是否加载结束
      offset: null,
      limit: 5
    }
  },

  methods: {
    async onLoad() {
      try {
        // 1.调用接口,获取列表数据
        const { data } = await getComments({
          type: this.type,
          source: this.source,
          offset: this.offset,
          limit: this.limit
        })
        // 2.得到的数据追加到List数组中
        const { results } = data.data
        this.list.push(...results)
        // 3.关闭Loading 状态
        this.loading = false
        // 4．判断数据是否全部加载完成
        if (results.length === 0) {
          // 4.1已完成==> finished设置为true
          this.finished = true
        } else {
          // 4.2未完成==>更新下一页的页码值
          this.offset = data.data.last_id
        }
      } catch (err) {
        this.loading = false
        this.error = true
      }
    }
  }
}
</script>
